<template>
  <base-breadcrumb :title="$route.meta.title">
    <!-- 样板验收记录编辑 -->
    <a-form-model
      ref="ruleForm"
      :model="form"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      :rules="editModel != 0 ? rules : {}"
      id="base-breadcrumb"
      style="position: relative"
    >
      <a-spin :spinning="loading[0] || loading[1]">
        <!-- 项目信息 -->
        <base-info
          ref="baseInfo"
          :disabled="editModel == 1"
          :form="form"
          :editModel="editModel != 2 && editModel == 1 ? 0 : editModel"
          :is-no-border="editModel=='0'"
          @companychange="handleChange"
        ></base-info>
        <!-- :editModel="editModel != 2 && (disabled && editModel == 1) ? 0 : editModel" -->
        <!-- 表格 -->
        <a-card :bordered="false" style="margin-bottom: 50px">
          <title-name title="样板工程验收信息"></title-name>
          <custom-form :isEmit="false" :formList="formList" :form="form" :editModel="editModel == 0 ? 'V' : ''">
            <template #name>
              <div v-if="editModel == 0" style="margin-top: -3px">{{ form.name }}</div>
              <a-row type="flex" align="middle" v-else>
                <div :style="{ width: editModel == 0 ? '100%' : 'calc(100% - 108px)' }">
                  <BaseInput v-model="form.name"></BaseInput>
                </div>
                <ChooseModel v-if="editModel != 0" :form="form" :mark="0" />
              </a-row>
            </template>
            <!-- 图片上传 -->
            <template #fileArrays>
              <div v-if="editModel == 0 && (!form.fileArrays || form.fileArrays.length < 1)" style="margin-top: -3px">
                无
              </div>
              <div v-else>
                <l-table
                  uploadType="image"
                  businessCode="QM06"
                  :disabled="editModel == 0"
                  :editModel="editModel"
                  :uploadArrys.sync="form.fileArrays"
                  multiple
                ></l-table>
              </div>
            </template>
          </custom-form>
        </a-card>
      </a-spin>
      <!-- 页脚操作栏 -->
      <div
        class="btn_box page-btn-right-top"
      >
        <BasePrintButton
          v-if="editModel == 0"
          :beforePrintFn="() => getPritContent('CSCEC8XN-EQ-B30604')"
          class="button_right"
        />
        <a-button
          :disabled="loading[0] || loading[1]"
          v-if="editModel == 1 && statusCode === '0'"
          type="danger"
          class="button_right"
          @click="handleRemove"
          >删除草稿</a-button
        >
        <a-button
          :loading="loading[0]"
          :disabled="loading[1]"
          v-if="(editModel == 1 && (statusCode === '0' || statusCode === '3')) || editModel == 2"
          type="primary"
          class="button_right"
          @click="handleSubmit(0)"
          >保存草稿</a-button
        >
        <a-button
          :loading="loading[1]"
          :disabled="loading[0]"
          v-if="(editModel == 1 && (statusCode === '0' || statusCode === '3')) || editModel == 2"
          type="primary"
          class="button_right"
          @click="handleSubmit(1)"
          >提交</a-button
        >
        <a-button type="primary" @click="handleClose">关闭</a-button>
      </div>
    </a-form-model>
  </base-breadcrumb>
</template>

<script>
import { acceptanceRecord, projectImplementationPlan } from '@/api/quality/sample' // api
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import BaseInfo from '@/components/businessComponents/BaseInfo' // 基础信息
import SelectSubcontractor from '@/components/Select/SelectSubcontractor' // 分包商
import SelectTeam from '@/components/Select/SelectTeam' // 班组
import BasePrintButton from '@/components/BasePrintButton' // 打印按钮
import ChooseModel from '../components/ChooseModel' // 选择样板信息

export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    BaseInfo,
    BasePrintButton,
    ChooseModel
  },
  data() {
    return {
      loading: { 0: false, 1: false }, // 请求加载框
      fetching: false, // 样板名称请求加载框
      editModel: 0, // 操作类型
      form: {
        viewName: ""
      }, // 表单
      statusCode: '', // 审批状态
      nameList: [], // 样板名称列表
      rules: {
        branchCompanyId: [{ required: true, message: '请选择分公司', trigger: 'change' }],
        projectId: [{ required: true, message: '请选择项目', trigger: 'change' }],
        name: [{ required: true, whitespace: true, message: '请输入样板名称', trigger: 'change' }],
        part: [{ required: true, whitespace: true, message: '请输入样板部位', trigger: 'change' }],
        subcontractorId: [{ required: true, message: '请选择劳务单位', trigger: 'change' }],
        monitorId: [{ required: true, message: '请选择班组', trigger: 'change' }],
        constructionDate: [{ required: true, message: '请选择施工时间', trigger: 'change' }],
        makeDate: [{ required: true, message: '请选择计划制作时间', trigger: 'change' }],
        content: [{ required: true, whitespace: true, message: '请输入验收记录', trigger: 'change' }],
        result: [{ required: true, whitespace: true, message: '请输入验收结论', trigger: 'change' }],
        fileArrays: [{ required: true, type: 'array', message: '请上传图片', trigger: 'blur' }]
      }, // 表单校验规则
      init: false, // 图片上传初始化控件
      checkInit: false // 样板计划项监听初始化
    }
  },
  watch: {
    'form.fileArrays'(e) {
      if (this.editModel != 0 && this.init) {
        this.$nextTick(() => {
          this.$refs.ruleForm?.validateField('fileArrays')
        })
      }
    },
    'form.name'(e) {
      if(this.init){
        if (this.form.chooseName && this.form.chooseName === e) {
          this.$nextTick(() => {
            this.$set(this.form, 'sampleStatus', '0')
            this.$set(this.form, 'sampleStatusName', '计划内')
            this.$set(this.form, 'planId', this.form.choosePlanId)
          })
        } else if (this.form.chooseName !== e) {
          this.$set(this.form, 'sampleStatus', '1')
          this.$set(this.form, 'sampleStatusName', '计划外')
          // console.log()
          if (this.form.planId) {
            // this.$set(this.form, 'planId', this.selectedRow?.[0]?.id)
            this.form.planId = void 0
          }
        }
      }
      // this.checkInit && this.checkName()
    }
  },
  computed: {
    // 是否禁用表单
    disabled() {
      // return this.nameList.map((item) => item.value)?.includes(this.form.name)
      return this.form.planId ? true : false
    },
    // 表单列表
    formList() {
      return [
        {
          slot: true,
          keyName: 'name',
          label: '样板名称'
        },
        {
          keyName: 'part',
          type: 'a-input',
          // disabled: this.disabled,
          label: '样板部位'
        },
        {
          keyName: 'makeDate',
          type: 'a-date-picker',
          // disabled: this.disabled,
          placeholder: '请选择日期',
          label: '计划制作时间',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
        {
          keyName: 'subcontractorId',
          // keyName: this.disabled ? 'subcontractor' : 'subcontractorId',
          viewName: 'subcontractor',
          type: SelectSubcontractor,
          // type: this.disabled ? 'BaseInput' : SelectSubcontractor,
          // disabled: this.disabled,
          placeholder: '请选择劳务单位',
          label: '劳务单位',
          attrs: {
            form: this.form,
            extraSubcontractor: {
              subContractorId: '-1',
              name: '分包单位未进场'
            },
            showSearch: true,
            isClear: this.editModel == 2
          },
          select: () => {
            // 劳务单位改变时，清空班组表单值
            this.$set(this.form, 'monitorId', '')
          }
        },
        {
          keyName: 'monitorId',
          viewName: 'monitor',
          type: this.form.subcontractorId === '-1' ? 'a-select' : SelectTeam,
          // type: this.disabled ? 'BaseInput' : SelectTeam,
          placeholder: '请选择劳务班组',
          label: '班组',
          data: [
            {
              value: '-1',
              label: '分包单位未进场'
            }
          ],
          // disabled: this.disabled,
          attrs:
            this.form.subcontractorId === '-1'
              ? { defaultValue: '-1' }
              : {
                  defaultValue: -1,
                  showSearch: true,
                  keyValue: ['projectId', 'subcontractorId'],
                  isEdit: this.editModel != 2,
                  isClear: this.editModel == 2
                }
        },
        {
          keyName: 'sampleStatusName',
          type: 'BaseInput',
          label: '样板状态',
          disabled: true
        },
        {
          keyName: 'constructionDate',
          type: 'a-date-picker',
          placeholder: '请选择日期',
          label: '施工时间',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
        {
          keyName: 'content',
          type: 'BaseTextarea',
          label: '样板验收记录',
          span: 24,
          attrs: {
            maxLength: 1000
          }
        },
        {
          keyName: 'result',
          type: 'BaseTextarea',
          label: '样板验收结论',
          span: 24
        },
        {
          keyName: 'fileArrays',
          slot: true,
          label: '图片上传',
          span: 24
        }
      ]
    }
  },
  mounted() {
    this.$route.meta.title = ['样板工程验收查看', '样板工程验收编辑', '样板工程验收添加'][this.editModel]
    // 不为添加时请求详情
    if (this.editModel != 2) {
      this.loading[0] = true
      acceptanceRecord
        .getDetail({ id: this.id })
        .then((res) => {
          this.loading[0] = false
          if (res.code === 200) {
            res.data.choosePlanId = res.data.planId
            // 若是计划内，则添加计划内样板默认名
            if(res.data.sampleStatus == '0'){
              res.data.chooseName = res.data.name
            }
            this.form = res.data
            this.form.viewName = this.form.branchCompanyName + "/" + this.form.projectName
            this.statusCode = res.data.statusCode
            this.$nextTick(() => {
              this.$set(this.form, 'sampleStatusName', ['计划内', '计划外'][res.data.sampleStatus])
              this.init = true
            })
          }
        })
        .catch((res) => {
          this.loading[0] = false
        })
    } else {
      this.$nextTick(() => {
        this.init = true
      })
    }
  },
  methods: {
    /**
     * 关闭
     */
     handleClose(){
      this.$router.go(-1)
     },
    /**
     * 检查模板名称状态
     */
    checkName() {
      let e = this.form.name
      this.$nextTick(() => {
        let list = ['makeDate', 'subcontractor', 'subcontractorId', 'monitor', 'monitorId', 'part', 'planId']
        if (this.nameList.length > 0 && this.nameList.map((item) => item.value)?.includes(e)) {
          let selectItem = this.nameList.find((item) => item.value === e)
          // 映射样板计划表单
          for (let item of list) {
            let value = selectItem[item === 'planId' ? 'id' : item]
            if (this.form[item]) {
              this.form[item] = value
            } else {
              this.$set(this.form, item, value)
            }
          }
          return
        }
        // 清空样板计划表单
        for (let item of list) {
          if (this.form[item]) {
            this.form[item] = ''
          } else {
            this.$set(this.form, item, '')
          }
        }
      })
    },
    /**
     * 获取样板列表
     */
    getModelList() {
      this.fetching = true
      projectImplementationPlan
        .down({ projectId: this.form.projectId })
        .then((res) => {
          this.fetching = false
          this.nameList = res.data?.map((item) => Object.assign(item, { text: item.name, value: item.id })) || []
          if (this.checkInit) {
            this.form.name && (this.form.name = '')
            this.checkName()
          } else {
            this.checkInit = true
          }
        })
        .catch(() => {
          this.fetching = false
        })
    },
    /**
     * 项目改变时
     */
    handleChange(branchCompanyId) {
      if (this.editModel != '2') {
        return false
      }
      this.form.branchCompanyId = branchCompanyId;
      let form = this.form
      if (form.subcontractorId) {
        form.subcontractorId = ''
        form.subcontractor = ''
      } else {
        this.$set(this.form, 'subcontractorId', '')
        this.$set(this.form, 'subcontractor', '')
      }
      if (form.monitorId) {
        form.monitorId = ''
        form.monitor = ''
      } else {
        this.$set(this.form, 'monitorId', '')
        this.$set(this.form, 'monitor', '')
      }
    },
    // /**
    //  * 样板名称选中改变时
    //  */
    // handleSelect(name, value) {
    //   if (name === 'name') {
    //     this.disabled = true
    //   }
    // },
    /**
     * 删除草稿
     */
    handleRemove() {
      this.$confirm({
        title: '温馨提示',
        content: '确定删除草稿？',
        onOk: () => {
          return acceptanceRecord.remove({ id: this.id }).then((res) => {
            this.$message.success('删除成功！')
            // 关闭当前页
            this.$multiTab.close()
          })
          // .catch((res) => {
          //   this.$message.warning('删除失败！')
          // })
        }
      })
    },
    /**
     * 提交表单
     */
    handleSubmit(statusCode) {
      let that = this
      let name = ['update', 'create'][that.editModel - 1] // 根据操作切换url地址
      // 校验表单
      that.$refs.ruleForm.validate((e) => {
        if (e || statusCode === 0) {
          statusCode === 0 && that.$refs.ruleForm.clearValidate()
          // 提交表单
          that.loading[statusCode] = true
          let form = that.$clone(that.form)
          form.statusCode = statusCode
          acceptanceRecord[name](form)
            .then((res) => {
              that.loading[statusCode] = false
              that.$message.success(['保存', '提交'][statusCode] + '成功！')
              that.$multiTab.close()
            })
            .catch((res) => {
              // that.$message.warning(['保存', '提交'][statusCode] + '失败!')
              that.loading[statusCode] = false
            })
        } else {
          this.$message.warning('数据填写不完整，不能提交')
        }
      })
    }
  }
}
</script>
